package com.fc.backingbeans

import groovy.transform.TypeChecked

import java.text.SimpleDateFormat

import javax.annotation.PostConstruct
import javax.faces.bean.SessionScoped

import org.primefaces.model.chart.CartesianChartModel
import org.primefaces.model.chart.ChartSeries
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import com.fc.entities.Measurement
import com.fc.entities.MeasurementType
import com.fc.service.MeasurementService
import com.fc.service.MeasurementTypeService
import com.fc.service.UserDetailsService

@Component("measurementController")
@SessionScoped
class MeasurementController {
	@Autowired
	private MeasurementService service
	@Autowired
	private MeasurementTypeService measurementTypeService
	@Autowired
	private UserDetailsService userService

	MeasurementType measurementType

	CartesianChartModel chartModel

	List<Measurement> getEntries() {
		def entries = service.findAllByTypeAndUser(measurementType, userService.currentUser)
		return entries
	}
	
	CartesianChartModel getChartModel() {
		if (chartModel == null) {
			refreshChart();
		}
		return chartModel
	}

	@PostConstruct
	private void init() {
		measurementType = measurementTypeService.findAll()[0]
	}

	void refreshChart() {
		chartModel = new CartesianChartModel()
		ChartSeries series = new ChartSeries()
		String label = measurementType.name
		series.setLabel(label)
		def measurements = service.findAllByTypeAndUser(measurementType, userService.currentUser)
		for (entry in measurements) {
			series.set(new SimpleDateFormat("yyyy.MM.dd HH:mm").format(entry.date), entry.value)
		}
		/* ha üres, dummy data kell, hogy renderelődjön a chart */
		if (measurements.isEmpty()) {
			series.set(0, 0)
		}
		chartModel.addSeries(series);
	}

	List<MeasurementType> findAll() {
		measurementTypeService.findAll()
	}
}
